package com.gexiaobao.pigeon.ui.fragment.match.training

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentTrainingSignUpDetailBinding
import com.gexiaobao.pigeon.ui.adapter.SignUpPigeonDetailAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogPageTurning
import com.gexiaobao.pigeon.viewmodel.TrainingInfoViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import kotlin.math.ceil

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 15:05
 * @Describe    : 训放赛-报名详情
 */
class FragmentSignUpDetail : BaseFragment<TrainingInfoViewModel, FragmentTrainingSignUpDetailBinding>() {
    private var mPassId = ""
    private var memberCode = ""
    private var searchNameStr = ""
    private val mAdapter: SignUpPigeonDetailAdapter by lazy { SignUpPigeonDetailAdapter(arrayListOf()) }

    private var mPageNo: Int = 1
    private var mPageTotal = 0
    private var mTotalNum = 0

    override fun initView(savedInstanceState: Bundle?) {
        val title = arguments?.getString("title")
        memberCode = arguments?.getString("memberCode").toString()
        searchNameStr = memberCode
        if (!title.isNullOrBlank()) {
            mDatabind.includeBar.toolbar.initClose(title) {
                nav().navigateUp()
            }
        }
        mDatabind.includeSearchEt.etSearch.setText(memberCode)
    }

    override fun initData() {
        super.initData()

        mDatabind.includeSearchEt.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchData()

                else -> {}
            }
            false
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter)
            .addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 0f)))

        mDatabind.layoutList.swipeRefreshLayout.init {
            mViewModel.getGatherListForHand(mPassId, searchNameStr, mPageNo)
        }

        mAdapter.addChildClickViewIds(R.id.tv_item_sign_up_pigeon_foster_name)
        mAdapter.addChildClickViewIds(R.id.tv_item_sign_up_pigeon_member_num)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_sign_up_pigeon_foster_name -> {
                    mPageNo = 1
                    searchNameStr = mAdapter.data[position].fosterName
                    onRefresh(mPageNo)
                    mDatabind.includeSearchEt.etSearch.setText(searchNameStr)
                    mDatabind.includeSearchEt.etSearch.setSelection(searchNameStr.length)
                    RxToast.showToast(searchNameStr)
                }

                R.id.tv_item_sign_up_pigeon_member_num -> {
                    mPageNo = 1
                    searchNameStr = mAdapter.data[position].memberNum
                    onRefresh(mPageNo)
                    mDatabind.includeSearchEt.etSearch.setText(searchNameStr)
                    mDatabind.includeSearchEt.etSearch.setSelection(searchNameStr.length)
                    RxToast.showToast(searchNameStr)
                }
            }
        }
    }

    private fun searchData() {
        hideSoftKeyboard(activity)
        searchNameStr = mDatabind.includeSearchEt.etSearch.text.toString()
        when {
            searchNameStr.isEmpty() -> showMessage(getString(R.string.input_search_content))
            else -> {
                showLoading(getString(R.string.loading))
                mViewModel.getGatherListForHand(mPassId, searchNameStr, mPageNo)
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mPassId = arguments?.getInt("id").toString()
        mPageNo = 1
        onRefresh(mPageNo)
    }

    private fun onRefresh(pageNo: Int) {
        showLoading(getString(R.string.loading))
        mViewModel.getGatherListForHand(mPassId, searchNameStr, pageNo)
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        mViewModel.gatherDetailResponse.observe(viewLifecycleOwner) {
            if (mDatabind.layoutList.swipeRefreshLayout.isRefreshing) {
                mDatabind.layoutList.swipeRefreshLayout.isRefreshing = false
            }
            mTotalNum = it.total
            mAdapter.setTotal(mTotalNum, mPageNo)
            mAdapter.setList(it.data)
            mAdapter.notifyDataSetChanged()
            mPageTotal = ceil(SettingUtil.div(mTotalNum.toDouble(), 50.00, 2)).toInt()//取整
            mDatabind.organizeSearchNumber.text =
                getString(R.string.tv_training_sign_pigeon_num) + it.total + getString(R.string.yu) + "    " + getString(R.string.altogether) + mPageTotal + getString(
                    R.string.page
                )
            mDatabind.layoutList.swipeRecyclerView.scrollToPosition(0)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.collectionResultPageAll,
            mDatabind.collectionResultPageMine,
            mDatabind.includeSearchEt.etSearchTv,
            mDatabind.includePage.tvFirstPage,
            mDatabind.includePage.tvPageUp,
            mDatabind.includePage.tvLastPage,
            mDatabind.includePage.tvThrough,
            mDatabind.includePage.tvNextPage,
        ) {
            when (it) {
                mDatabind.includePage.tvThrough -> showDialogPageTurning()
                mDatabind.includePage.tvLastPage -> {
                    mPageNo = mPageTotal
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includePage.tvNextPage -> {
                    if (mPageNo == mPageTotal) {
                        RxToast.warning(getString(R.string.last_page))
                        return@setOnclickNoRepeat
                    }
                    mPageNo++
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includePage.tvPageUp -> {
                    if (mPageNo == 1) {
                        RxToast.warning(getString(R.string.first_page))
                        return@setOnclickNoRepeat
                    }
                    mPageNo--
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includePage.tvFirstPage -> {
                    mPageNo = 1
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.collectionResultPageAll -> {
                    mPageNo = 1
                    searchNameStr = ""
                    mDatabind.includeSearchEt.etSearch.setText("")
                    onRefresh(mPageNo)
                }

                mDatabind.collectionResultPageMine -> {
                    mPageNo = 1
                    searchNameStr = memberCode
                    mDatabind.includeSearchEt.etSearch.setText(memberCode)
                    mDatabind.includeSearchEt.etSearch.setSelection(memberCode.length)
                    onRefresh(mPageNo)
                }

                mDatabind.includeSearchEt.etSearchTv -> {
                    mPageNo = 1
                    if (mDatabind.includeSearchEt.etSearch.text.isNullOrEmpty()) {
                        RxToast.showToast(getString(R.string.input_search_content))
                        return@setOnclickNoRepeat
                    }
                    searchNameStr = mDatabind.includeSearchEt.etSearch.text.toString()
                    onRefresh(mPageNo)
                }
            }
        }
    }

    private fun showDialogPageTurning() {
        var pageNumber: Int
        val dialog = RxDialogPageTurning(context)
        dialog.setTitle(getString(R.string.chose_look_page) + "\n" + getString(R.string.altogether) + mPageTotal + getString(R.string.page))
        dialog.setPlusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (pageNumber > mPageTotal) {
                RxToast.warning(getString(R.string.has_exceeded_the_total_page))
                return@setPlusListener
            }
            if (pageNumber == mPageTotal) {
                RxToast.warning(getString(R.string.last_page))
                return@setPlusListener
            }
            pageNumber++
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setMinusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }

            if (pageNumber == 1) {
                RxToast.warning(getString(R.string.first_page))
                return@setMinusListener
            }
            pageNumber--
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setSureListener {
            mPageNo = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (mPageNo > mPageTotal) {
                RxToast.warning(getString(R.string.chose_look_page))
                return@setSureListener
            }
            mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
            onRefresh(mPageNo)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }
}